package com.zeroext.security.dao.impl;

import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.zeroext.dao.common.BaseDAO;
import com.zeroext.dao.common.SimplePage;
import com.zeroext.security.dao.UserDAO;
import com.zeroext.security.entity.User;
import com.zeroext.security.entity.UserInfo;

public class UserDAOImpl extends BaseDAO implements UserDAO {

    public User getUser(Long id) {
        Session session = this.getSession();
        Criteria cri = session.createCriteria(User.class);
        cri.add(Restrictions.eq("id", id));
        User user = (User) cri.uniqueResult();
        return user;
    }

    public User getUserBy(String name, Object value) {
        Session session = this.getSession();
        Criteria cri = session.createCriteria(User.class);
        cri.add(Restrictions.eq(name, value));
        User user = (User) cri.uniqueResult();
        return user;
    }

    public UserInfo getUserInfo(Long userId) {
        Session session = this.getSession();
        Criteria cri = session.createCriteria(UserInfo.class);
        cri.add(Restrictions.eq("userId", userId));
        UserInfo userInfo = (UserInfo) cri.uniqueResult();
        return userInfo;
    }

    @SuppressWarnings("unchecked")
    public SimplePage<User> listUser(int begin, int pageSize,
            Map<String, Object> queryMap) {
        Session session = this.getSession();
        Criteria cri = session.createCriteria(User.class);
        if(queryMap!=null){
            for(String name : queryMap.keySet()){
                Object value = queryMap.get(name);
                cri.add(Restrictions.eq(name, value));
            }
        }
        cri.setFirstResult(begin);
        cri.setMaxResults(pageSize);
        List<User> users = cri.list();
        cri.setFirstResult(0);
        long total = Long.valueOf(cri.setProjection(Projections.rowCount()).uniqueResult().toString());
        SimplePage<User> page = new SimplePage<User>();
        page.setData(users);
        page.setTotal(total);
        return page;
    }

    public User saveUser(User user) {
        this.getSession().saveOrUpdate(user);
        return user;
    }

    public UserInfo saveUserInfo(UserInfo userInfo) {
        this.getSession().saveOrUpdate(userInfo);
        return userInfo;
    }

}
